package be.groept.ace.cursusplanning.controller;

/**
 * @author Gouke Leplat
 */

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

import Exceptions.ConfigurationException;


public class AppConfig {
	
	private String configFile;
	private String connectionString;
	private String naamPersistentieController;
	private Map<String, String> persistentieProviderClassNames = new TreeMap<String, String>(); 

	
	public AppConfig(String configFile) throws ConfigurationException {
		this.configFile = configFile;
		readconfigurationFile();
	}
	
	private void readconfigurationFile() throws ConfigurationException{
		
		File file = new File(configFile);
		
		try {
			
			if (file.createNewFile()){
				throw new ConfigurationException("Er is geen configuratiebestand gevonden");
			}
			
			Scanner mainScanner = new Scanner(file);
			String block;
			
			while (mainScanner.hasNext()){
				Scanner regel = new Scanner(mainScanner.nextLine());
				regel.useDelimiter(";");
				
				if (!regel.hasNext()) continue;
				
				block = regel.next(); // identifier
				
				if (block.equalsIgnoreCase("@PersistencyController")){
					setNaamPersistentieController(regel);
				}
				else if (block.equalsIgnoreCase("@PersistencyProviders")){
					addpersistentieProviderClassName(regel);
				}
				else if (block.equalsIgnoreCase("@Connectionstring")){
					setConnectionString(regel);
				}
				else{
					// Eventuele andere settings
				}

			}

		} catch (IOException e) {
			// TODO AppConfig Auto-generated catch block: APpConfig
			e.printStackTrace();
		}
		
	}
	
	private void setNaamPersistentieController(Scanner regel){
		String next = regel.next();
		this.naamPersistentieController = next;
	}
	private void addpersistentieProviderClassName(Scanner regel){
		String className = regel.next();
		String providerName = regel.next();

		persistentieProviderClassNames.put(className, providerName);

	}
	
	public String getNaamPersistentieController(){
		return naamPersistentieController;
	}
	
	public  Map<String, String> getPersistentieProviderClassNames(){
		return persistentieProviderClassNames;
	}
	
	public String getPersistentieProviderClassName(String className){
		if (persistentieProviderClassNames.containsKey(className)){
			return persistentieProviderClassNames.get(className);
		}
		else{
			return null;
		}
	}
	public String getConnectionString() {
		return connectionString;
	}

	private void setConnectionString(Scanner regel) {
		String next = regel.next();
		this.connectionString = next;
	}


}
